import { history } from 'umi';
import request from './http';
import { getNavConfig as navConfig } from './config';
import { Toast } from 'antd-mobile';
import { customAddShoppingCart } from '../common/apis';


// 是否是管理后台
export const isAdmin = location.pathname.startsWith("/view/admin");

/**
 * 判断是否是登录页
 */
export const checkIsLoginPage = () => {
    return ["/view/admin/login", "/view/custom/login", "/view/login"].includes(location.pathname);
}

/**
 * 页面跳转
 * @param {string} url 页面地址
 * @param {boolean} isReload 是否刷新页面
 * @param {boolean} isUseOriginUrl 是否使用原地址
 * @returns 
 */
export const goTo = (url, isReload, isUseOriginUrl) => {
    if (!url) {
        return;
    }

    if (!isUseOriginUrl) {
        if (location.pathname.startsWith('/view/admin')) {
            url = `/view/admin${url}`;
        } else {
            url = `/view${url}`;
        }
    }

    if (isReload) {
        location.href = url;
    } else {
        history.push(url);
    }
}

/**
 * 跳转登录页
 */
export const toLogin = () => {
    goTo(`/login?callback=${encodeURIComponent(location.href)}`, true);
};

/**
 * 设置登录成功标识
 */
export const setLoginSuccessFlag = () => {
    localStorage.setItem("babyLoveToken", "1");
};

/**
 * 删除登录成功标识
 */
export const removeLoginSuccessFlag = () => {
    localStorage.removeItem("babyLoveToken");
};

/**
 * 判断是否登录
 */
export const checkIsLogin = () => {
    return !!localStorage.getItem("babyLoveToken");
};


/**
 * 添加购物车
 * @returns 
 */
export const addShoppingCartCode = async () => {
    const { data } = await request.post(customAddShoppingCart);

    return data ? data.shoppingCartCode : null;
}

/**
 * 获取本地的购物车编码
 * @returns 
 */
export const getShoppingCartCode = async () => {
    let shoppingCartCode = localStorage.getItem('babyloveShoppingCartCode');
    if (!shoppingCartCode) {
        shoppingCartCode = await addShoppingCartCode();
    }
    if (!shoppingCartCode) {
        return Toast.show({
            icon: 'fail',
            content: '添加失败，请稍后再试',
        });
    }
    localStorage.setItem('babyloveShoppingCartCode', shoppingCartCode);
    return shoppingCartCode;
}

/**
 * 设置本地的购物车编码
 * @param {string} shoppingCartCode 
 * @returns 
 */
export const setShoppingCartCode = (shoppingCartCode) => {
    if (!shoppingCartCode) {
        return;
    }

    localStorage.setItem('babyloveShoppingCartCode', shoppingCartCode);
}

/**
 * 设置管理后台本地的购物车编码
 * @param {string} shoppingCartCode 
 * @returns 
 */
export const setAdminShoppingCartCode = (shoppingCartCode) => {
    if (!shoppingCartCode) {
        return;
    }

    localStorage.setItem('babyloveAdminShoppingCartCode', shoppingCartCode);
}

/**
 * 获取管理后台本地的购物车编码
 * @returns 
 */
export const getAdminShoppingCartCode = () => {
    return localStorage.getItem('babyloveAdminShoppingCartCode');
}

/**
 * 删除管理后台本地的购物车编码
 * @returns 
 */
export const removeAdminShoppingCartCode = () => {
    localStorage.removeItem('babyloveAdminShoppingCartCode');
}

/**
 * 获取页面底部导航数据
 */
export const getNavConfig = async () => {
    const shoppingCartCode = await getShoppingCartCode();
    const config = navConfig(shoppingCartCode);
    if (isAdmin) {
        return config.admin;
    }

    return config.custom;
}

/**
 * 复制
 */
export const copy = (content) => {
    if (!content) {
        return false;
    }

    try {
        let input = document.createElement('input');
        input.value = content;
        input.style.height = 0;
        document.body.append(input);
        input.select();
        document.execCommand('Copy');
        input.remove();
        return true;
    } catch (error) {
        return false;
    }
}

/**
 * 判断是否为移动设备
 * @returns 
 */
export const isMobile = () => {
    return (
        typeof window.orientation !== "undefined" || // 检查window有无orientation属性，此属性在移动设备上一般存在
        navigator.userAgent.indexOf('Mobile') !== -1 || // 检查userAgent中是否包含'Mobile'关键字
        navigator.userAgent.match(/AppleWebKit.*Mobile.*/) || // 匹配AppleWebKit内核且包含Mobile的设备
        navigator.userAgent.match(/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/) // 匹配其他已知移动设备品牌
    );
}

/**
 * 忽略年份对日期数组排序
 * @param {Array} arr 数组
 * @param {string} dateField 日期字段
 * @returns 
 */
export const sortByDateIgnoringYear = (arr, dateField) => {
    if (!Array.isArray(arr) || arr.length < 1) {
        return arr;
    }
    if (!dateField) {
        throw new Error('dateField 参数不能为空');
    }
    if (!(dateField in arr[0])) {
        throw new Error('数组中不包含 dateField 属性，请检查');
    }
    const now = new Date();
    const currentMonth = now.getMonth() + 1;
    const currentDate = now.getDate();
    const currentHours = now.getHours();
    const currentMinutes = now.getMinutes();
    const currentSeconds = now.getSeconds();

    arr.sort((a, b) => {
        try {
            // 获取时间部分 HH:mm:ss
            if(!a[dateField]){
                return 1;
            }
            if(!b[dateField]){
                return -1;
            }
            const timeA = a[dateField].split(' ')[1];
            const timeB = b[dateField].split(' ')[1];

            // 构造完整的日期时间字符串进行比较，忽略年份，但包括时、分、秒
            const fullDateA = `2000-${a[dateField].split('-')[1]}-${a[dateField].split(' ')[0].split('-')[2]} ${timeA}`;
            const fullDateB = `2000-${b[dateField].split('-')[1]}-${b[dateField].split(' ')[0].split('-')[2]} ${timeB}`;

            // 将构造的字符串转换为日期对象
            const parsedDateA = new Date(fullDateA);
            const parsedDateB = new Date(fullDateB);

            // 计算与当前时间的差距，越小的排在前面
            // 这里直接比较Date对象即可，因为Date对象的比较会自动考虑年月日时分秒
            const diffA = Math.abs(parsedDateA - new Date(`2000-${currentMonth}-${currentDate} ${currentHours}:${currentMinutes}:${currentSeconds}`));
            const diffB = Math.abs(parsedDateB - new Date(`2000-${currentMonth}-${currentDate} ${currentHours}:${currentMinutes}:${currentSeconds}`));

            return diffA - diffB;
        } catch (error) {
        }
        return 0;
    });

    return arr;
}
